﻿define(
	[
		'require'
	],
	function(require){
		function dateCellFormatter(args, column){
			if (args.row.type & $.wijmo.wijgrid.rowType.data) {
				var data = args.row.data,
					dataKey = column.dataKey,
					formatedTime = APM.util.formatDate(data[dataKey], "yyyy-MM-dd H:mm:ss");
				data["_formatted_"+dataKey] = formatedTime;
				args.$container.append(formatedTime);
				return true;
			}
		}  
		var Controller = Ember.Controller.extend({
			needs: ["businessDetail"],

			business: Ember.computed.alias('controllers.businessDetail.model'),

			pinTimePoint: Ember.computed.alias('controllers.businessDetail.pinTimePoint'),

			businessIdChange: Ember.observer("business.id", function(){
				this.set('keyWord', '');
			}),

			initTime: function(){
		        var ctrl = this;
		        var startDate = ctrl.get("startDate");
		        var endDate = ctrl.get("endDate");
		        if(this.get("clickTimePoint") != null ){
		        	var date = new Date(this.get("clickTimePoint"));
		        	ctrl.set("endDate",new Date(+date+60000));
		        	if((isNaN(startDate))){
		        		ctrl.set("startDate",new Date(+date+60000)-60000);
		        	}else{
		        		ctrl.set("startDate",new Date(+date+60000)-(Math.abs(+endDate-(+startDate))));
		        	}
		        	
		        	
		        	setTimeout(function(){
		        		var startDate = APM.util.formatDate(new Date(+ctrl.get("startDate")), "yyyy/MM/dd H:mm");
		        		var endDate = APM.util.formatDate(new Date(+ctrl.get("endDate")), "yyyy/MM/dd H:mm");
		        		$('#config-demo').val(startDate+' - '+endDate);
		        	});
		        	
		        }else{
		        	var sdate = new Date(new Date() - timeD_value - 60000-60000);
			        sdate.setSeconds(0);
			        sdate.setMilliseconds(0); 
			        ctrl.set("startDate",new Date(+sdate));
			        var edate = new Date(new Date() - timeD_value-60000);
			        edate.setSeconds(0);
			        edate.setMilliseconds(0); 
			        ctrl.set("endDate",new Date(+edate));
		        }
		    },

			clickTimePoint: Ember.computed.oneWay('controllers.businessDetail.clickTimePoint'),

			errorcodes: Ember.A(),

			channelValue: '',

			pageSize: 10,

			transactionChannel: Ember.A(),
			/*
				列配置
			*/
			perfColumns: [
				{
					headerText: "交易渠道名称",
					dataKey:"name",
					textAlignment:"left",
					cellFormatter:function(args){
						if (args.row.type & $.wijmo.wijgrid.rowType.data) {
							var ctrl = this.get("controller");
							var data = args.row.data.name;
							if(data == 0){
								data = 0;
							}else if(!data){
								data = "-";
							}
							var cb = $("<div ></div>").text(data);
							cb.appendTo(args.$container);
							return true;
						}
					}
				},
				{
					headerText: "交易量",
					dataKey:"throughput",
					textAlignment:"right",
					cellFormatter:function(args){
						if (args.row.type & $.wijmo.wijgrid.rowType.data) {
							var ctrl = this.get("controller");
							var data = args.row.data.throughput;
							if(data == 0){
								data = 0;
							}else if(!data){
								data = "-";
							}
							var cb = $("<div ></div>").text(data);
							cb.appendTo(args.$container);
							return true;
						}
					}
				},
				{
					headerText: "平均响应时间",
					dataKey:"responseTime",
					_fmtType: "transform_time",
					textAlignment:"right",
					cellFormatter: APM.util.indicatorCellFormatter
				},
				{
					headerText: "成功率",
					dataKey:"successRate",
					textAlignment:"right",
					cellFormatter:function(args){
						if (args.row.type & $.wijmo.wijgrid.rowType.data) {
							var ctrl = this.get("controller");
							var data = args.row.data.successRate;
							if(data == 0){
								data = 0;
							}else if(!data){
								data = "-";
							}
							var cb = $("<div ></div>").text(data);
							cb.appendTo(args.$container);
							return true;
						}
					}
				},
				{
					headerText: "错误数",
					dataKey:"error",
					textAlignment:"right",
					cellFormatter:function(args){
						if (args.row.type & $.wijmo.wijgrid.rowType.data) {
							var ctrl = this.get("controller");
							var data = args.row.data.performance["business/error/count"];
							if(data == 0){
								data = 0;
							}else if(!data){
								data = "-";
							}
							var cb = $("<div ></div>").text(data);
							cb.appendTo(args.$container);
							return true;
						}
					}
				}
			],
			serviceId: function(){
				var serviceId = this.get("model.id");
				var arrId = serviceId.split('-');
				return serviceId = arrId[arrId.length-1];
			},

			keyUpEnent: function(){
				var ctrl = this;
				setTimeout(function(){
					$("#mouseKeyUp").on("keyup",function(event){
						if(event.keyCode == 13){
							ctrl.requireData();
						};
					});
				},0)
			},
			
			requireData: function(){
				var ctrl = this,
					serviceId = ctrl.get("model.id"),
					typeValue = ctrl.get("typeValue");

				var params = {
					"appId":this.get("business.id"),
					"serviceId":serviceId,
					"keyWord": this.get("keyWord"),
				    "startDate": +this.get("startDate"),
					"endDate": +this.get("endDate"),
					"transactionType": typeValue,
					"pageIndex": this.get("pageIndex"),
				    "pageSize": this.get("pageSize"),
				     "orderBy": this.get("orderBy"),
					"desc": this.get("desc")
				};

				if( isLocalDebugModel ){
					params = undefined;
				}

				return this.store.ajax("GET", "trades/channel", params)
				.then(function(response){
					var result = response.result || [],
						successRate = "business/success/rate",
						responseTime = "business/response_time/avg",
						error = "business/error/count",
						throughput = "business/throughput/total";
						
						result.forEach(function(node){
							if(node.performance[error] == 0){
								node.error = node.performance[error];
							}else if(!node.performance[error]){
								node.error = node.performance[error];
							}
							if(node.performance[responseTime] == 0){
								node.responseTime = node.performance[responseTime];
							}else if(node.performance[responseTime]){
								node.responseTime = node.performance[responseTime];
							}
							if(node.performance[throughput] == 0){
								node.throughput = node.performance[throughput];
							}else if(node.performance[throughput]){
								node.throughput = node.performance[throughput];
							}
							if(node.performance[successRate] == 0){
								node.successRate = 0+"%";
							}else if(!node.performance[successRate]){
								node.successRate = "-";
							}else{
								node.successRate = node.performance[successRate]+"%";
							}
						});

					if (result.length == 0) {
						ctrl.set("pageIndex",0);
						ctrl.set("pageSize",10);
						ctrl.set("totalRows",0);//设置为0显示没有数据
					} else {
						ctrl.set("pageIndex",response.meta.pageIndex);
						ctrl.set("pageSize",response.meta.pageSize);
						ctrl.set("totalRows",response.meta.total);
					}
					ctrl.set("errorcodes",result);
				
					return response;
				});
			},

			transactionTypeRequireAlerts: function(params){
				return this.store.ajax("GET","transaction/channel",params);
			},

			isOnce:true,

			actions: {
				search: function() {
					this.set("pageIndex", 0);
					this.requireData();
				},
				gridSorted: function(e, data, view){
					view.ensureControl(false);
					var dataKey = data.column.dataKey;
					switch(dataKey){
						case "responseTime":
						dataKey = "business/response_time/avg";
						break;
						case "error":
						dataKey = "business/error/count";
						break;
						case "throughput":
						dataKey = "business/throughput/total";
						break;
						case "successRate":
						dataKey = "business/success/rate";
						break;
						default:
						return;
						break;
					}
					this.set("orderBy", dataKey);
					this.set("desc", data.sortDirection=="descending"||undefined);
					this.requireData();
				},
				pageIndexChanged: function(e, data, view){
					var pageNo = data.newPageIndex;
					this.set("pageIndex", pageNo);
					this.requireData();
				},
				scvDownload: function(){
					var ctrl = this;
					confirmDialog("确定要下载该模板文件吗？")
					.then(function(){
						var url="/front/rest/apm/configs/downloadIPMod?token="+encodeURIComponent($.cookie("token"));
						window.location.href =url;
					});
				},
				timePointChange: function(timeRange){
					this.set("startDate",timeRange.startDate);
					this.set("endDate",timeRange.endDate);
			
					this.requireData();
				},
				
				timeRangesChange: function(timeRange){
					var ctrl = this;
					var pinTimePoint = ctrl.get("controllers.businessDetail").pinTimePoint;

						ctrl.set("startDate", timeRange.startDate);
						ctrl.set("endDate", timeRange.endDate);
			
					
					var view = Broada.getView("businessTimeRangesTopo");
					if(ctrl.get("pinTimePoint") != timeRange.startDate){
						ctrl.set("pinTimePoint", null);
					}


					ctrl.set("pageIndex", 0);
					ctrl.requireData();
					// var isOnce = ctrl.get('isOnce');
					// if(isOnce){
					// 	ctrl.transactionTypeRequireAlerts({
					// 		"serviceId":serviceId
					// 	}).then(function(response){
						
					// 		var applications = response.transcationChannel;

							
					// 		ctrl.set("transcationChannel",Ember.A(applications));
					// 	});
					// 	ctrl.set('isOnce',false);
					// }
				}
			}
		});

		APM.BusinessDetailNodedetailChannelController = Controller;
		return Controller;
	}
);